package com.zf.yichat.api.controller.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.*;
import com.zf.yichat.api.dto.resp.ChatroomDto;
import com.zf.yichat.dto.ChatroomUserDto;
import com.zf.yichat.dto.MessageUnreadDto;
import com.zf.yichat.mapper.*;
import com.zf.yichat.model.*;
import com.zf.yichat.service.*;
import com.zf.yichat.service.config.ChatroomService;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.service.config.RongCloudApplication;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.common.GeneralUtils;
import com.zf.yichat.utils.common.MD5Util;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 17:27 2019/6/17 2019
 */
@RestController
@RequestMapping("message")
@Slf4j
public class MessageController extends BaseController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private ImApiService imApiService;

    @Autowired
    private ConfigSet configSet;

    @Autowired
    private OssService ossService;

    @Autowired
    private ChatroomService chatroomService;

    @Resource
    private MessageChatroomAdminUserMapper messageChatroomAdminUserMapper;

    @Resource
    private UserJoinChatroomMapper userJoinChatroomMapper;

    @Resource
    private UserJoinChatroomApplyMapper userJoinChatroomApplyMapper;

    @Resource
    private MessageChatroomMapper messageChatroomMapper;

    @Autowired
    private RongCloudApplication rongCloudApplication;

    private static final String robot_sign = "001";

    @PostMapping("upload")
    public FsResponse upload(@RequestBody MessageUploadRequest params) {
        params.valid();

        Message message = new Message();
        message.setMessageId(params.getMessageId());
        message.setContent(params.getContent());
        message.setTime(params.getTime());
        message.setReferId(Long.parseLong(params.getReferId()));
        message.setReferType(params.getReferType());
        message.setUserId(getUserId());
        return messageService.save(message, false);

    }


    //历史消息
    @PostMapping("list")
    public FsResponse list(@RequestBody MessageListRequest params) {
        params.valid();
        //FsResponse response = messageService.selectMyList(FsPage.init(params.getPageNo(), params.getPageSize()), params.getReferType(), params.getReferId(), params.getTime(), getUserId(), true);

        /*if (response.getCount() > 0) {
            Collections.reverse((List<MessageListDto>) (response.getData()));

        }*/

        //单聊
        if (params.getReferType() == 1) {
            return FsResponseGen.successData(messageService.selectSingleHistoryList(params.getPageNo(), Long.parseLong(params.getReferId()), params.getTime(), getUserId()));
        }

        return FsResponseGen.successData(messageService.selectHistoryList(params.getPageNo(),Integer.parseInt(params.getReferId()),params.getTime(),getUserId()));
    }

    @PostMapping("search/list")
    public FsResponse searchList(@RequestBody MessageSearchListRequest params) {
        params.valid();

        return messageService.selectSearchList(FsPage.init(params.getPageNo(), params.getPageSize()), GeneralUtils.splitIntExcludeEmpty(params.getGroupIds()), params.getSearchContent(), getUserId());
    }

    @PostMapping("update")
    public FsResponse cancle(@RequestBody MessageCancleRequest params) {
        params.valid();

        messageService.cancle(params.getMessageId(), getUserId(), params.getContent());
        return FsResponseGen.success();
    }

    @PostMapping("del/time")
    public FsResponse delTime(@RequestBody MessageDelTimeRequest params) {
        params.valid();

        messageService.saveDelTime(getUserId(), params.getReferType(), params.getReferId(), params.getTime());
        return FsResponseGen.success();
    }


    @PostMapping("delete")
    public FsResponse deleteMessage(@RequestBody MessageCancleRequest params) {
        params.valid();

        messageService.deleteMsg(params.getMessageId());
        return FsResponseGen.success();
    }




    //未读消息数
    @PostMapping("unread/list")
    @Deprecated
    public FsResponse unreadList() {

        List<Integer> gids = Optional.ofNullable(groupService.selectGroupByUserId(getUserId())).map(v -> v.stream().map(RcGroupMembers::getGroupid).collect(Collectors.toList())).orElse(new ArrayList<>(0));
        Long time = userService.getTimestamp(getUserId());
        FsResponse res = FsResponseGen.successData(DtoChangeUtils.getList(gids, v -> {
            MessageUnreadDto dto = new MessageUnreadDto();
            FsResponse response = messageService.selectList(FsPage.init(1, 20), 2, String.valueOf(v), time, getUserId(), false);
            dto.setUnreadCount(response.getCount().intValue());
            //dto.setList((List<MessageListDto>) response.getData());
            dto.setGroupId(v);
            /*if (dto.getUnreadCount() > 0) {
                dto.setLastmessage(((List<MessageListDto>) response.getData()).get(0));
            }*/
            return dto;
        }));

        userService.updateTimestamp(getUserId(), System.currentTimeMillis());

        return res;
    }


    @PostMapping("group/send")
    public FsResponse sendTextRobot(@RequestBody MessageSendGroupRequest params) throws Exception {

        if (Objects.isNull(params.getGroupId()) || Objects.isNull(params.getUserId())
                || StringUtils.isBlank(params.getText()) || StringUtils.isBlank(params.getSign())) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_PARAM_ERROR);
        }

        //校验key
        if (!StringUtils.equals(MD5Util.string2MD5(params.getUserId() + configSet.getKey().getMessage()), params.getSign())) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_KEY_ERROR);
        }


        User user = userService.selectById(N3d.decode(params.getUserId()));
        if (Objects.isNull(user)) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_PARAM_ERROR);
        }

        MessageBodyDto dto = new MessageBodyDto();

        MessageBodyDto.Ext ext = dto.new Ext();
        ext.setAvatar(user.getAvatar());
        ext.setNick(user.getNick());
        ext.setUserId(user.getId().toString());

        MessageBodyDto.Body body = dto.new Body();
        body.setContent(params.getText());


        MessageBodyDto.Data data = dto.new Data();
        data.setExt(ext);
        data.setBody(body);
        data.setChatType(2);
        data.setMsgType(2001);
        data.setMsgId(UUID.randomUUID().toString() + robot_sign);
        data.setFrom(params.getUserId().toString());
        data.setTo(String.valueOf(params.getGroupId()));


        dto.setData(data);
        dto.setType(2000);

        //发送消息
        imApiService.sendRobotMsg(2, params.getGroupId().longValue(), URLEncoder.encode(JSON.toJSONString(dto)));


        Message save=new Message();
        save.setContent( URLEncoder.encode(JSON.toJSONString(dto)));
        save.setUserId(N3d.decode(params.getUserId()));
        save.setReferType(2);
        save.setReferId(params.getGroupId().longValue());
        save.setMessageId(data.getMsgId());
        save.setTime(System.currentTimeMillis());
        //保存历史消息
        messageService.save(save, false);

        return FsResponseGen.success();

    }


    /**
     * 获取存活的聊天室
     * @return
     */
    @RequestMapping("/chatroom/query")
    @ResponseBody
    public FsResponse chatroomQuery() {
        try {
            List<MessageChatroom> chatroomList = chatroomService.getChatroomList();
            User user=userService.selectById(getUserId());

            List<MessageChatroom> returnchatroomList =new ArrayList<>();
            if("BR6B6".equals(user.getRecommendCode())){
                for(MessageChatroom messageChatroom:chatroomList){
                    if( messageChatroom.getChatroomIdNum()==800700L&&messageChatroom.getStatus()==1){
                        returnchatroomList.add(messageChatroom);
                    }
                    if( messageChatroom.getChatroomIdNum()==800600L&&messageChatroom.getStatus()==1){
                        returnchatroomList.add(messageChatroom);
                    }
                    if( messageChatroom.getChatroomIdNum()==800500L&&messageChatroom.getStatus()==1){
                        returnchatroomList.add(messageChatroom);
                    }

                }
                return FsResponseGen.successData(returnchatroomList);
            }else if("BR8A8".equals(user.getRecommendCode())){
                for(MessageChatroom messageChatroom:chatroomList){

                    if( messageChatroom.getChatroomIdNum()==800400L&&messageChatroom.getStatus()==1){
                        returnchatroomList.add(messageChatroom);
                    }

                    if( messageChatroom.getChatroomIdNum()==800300L&&messageChatroom.getStatus()==1){
                        returnchatroomList.add(messageChatroom);
                    }

                }
                return FsResponseGen.successData(returnchatroomList);
            }
            return FsResponseGen.successData(chatroomList);
        } catch (Exception e) {
            log.error("获取存活的聊天室失败");
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 获取存活的聊天室的管理员列表
     * @return
     */
    @RequestMapping("/chatroom/queryAdminList")
    @ResponseBody
    public FsResponse queryAdminList(@RequestBody ChatroomRequest params) {
        try {
            String chatroomId = params.getChatroomId();
            List<MessageChatroomAdminUser> chatroomAdminUsers = chatroomService.queryAdminListByChat(chatroomId);

            ArrayList<ChatroomDto> chatroomDtos = new ArrayList<>();

            chatroomAdminUsers.stream().forEach(data -> {
                try {
                    Long userId = data.getUserId();

                    ChatroomDto chatroomDto = new ChatroomDto();
                    chatroomDto.setUserId(N3d.encode(userId));
                    chatroomDto.setChatroomId(data.getChatroomId());
                    chatroomDtos.add(chatroomDto);
                } catch (Exception e) {
                    log.error("获取存活的聊天室的管理员列表中userId加密失败！");
                }
            });

            return FsResponseGen.successData(chatroomDtos);
        } catch (Exception e) {
            log.error("获取聊天室管理员失败！", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 查询保活聊天室
     * @return
     */
    @RequestMapping("/chatroom/keepalive/query")
    @ResponseBody
    public FsResponse keepaliveQuery(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/keepalive/query");

            // 解析响应数据
            String response = rongCloudApplication.executeReq(httpPost);

            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 添加保活聊天室
     * @return
     */
    @RequestMapping("/chatroom/keepalive/add")
    @ResponseBody
    public FsResponse keepaliveAdd(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/keepalive/add");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // 解析响应数据
            String response = rongCloudApplication.executeReq(httpPost);

            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 移除保活聊天室
     * @return
     */
    @RequestMapping("/chatroom/keepalive/remove")
    @ResponseBody
    public FsResponse keepaliveRemove(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/keepalive/remove");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // 解析响应数据
            String response = rongCloudApplication.executeReq(httpPost);

            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 添加全体禁言聊天室
     * @return
     */
    @RequestMapping("/chatroom/ban/add")
    @ResponseBody
    public FsResponse banAdd(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/ban/add");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            params.add(new BasicNameValuePair("userIds", request.getUserId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 移除全体禁言聊天室
     * @return
     */
    @RequestMapping("/chatroom/ban/rollback")
    @ResponseBody
    public FsResponse banRollback(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/ban/rollback");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 聊天室禁言状态检查
     * 禁言状态，1 为全体禁言、0 为非全体禁言
     * @return
     */
    @RequestMapping("/chatroom/ban/check")
    @ResponseBody
    public FsResponse banCheck(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/ban/check");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 查询聊天室禁言用户列表
     * @return
     */
    @RequestMapping("/chatroom/gag/list")
    @ResponseBody
    public FsResponse gagList(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/gag/list");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 成员禁言管理
     * @return
     */
    @RequestMapping("/chatroom/gag/add")
    @ResponseBody
    public FsResponse gagAdd(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/gag/add");
            String minute = request.getMinute();
            if (StringUtils.isBlank(minute)){
                minute = "0";
            }
            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", request.getUserId()));
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            params.add(new BasicNameValuePair("minute", minute));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 解除禁言指定聊天室用户
     * @return
     */
    @RequestMapping("/chatroom/gag/rollback")
    @ResponseBody
    public FsResponse gagRollback(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/gag/rollback");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", request.getUserId()));
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 查询被封禁聊天室成员，返回用户id和昵称
     * @return
     */
    @RequestMapping("/chatroom/user/block/list")
    @ResponseBody
    public FsResponse blockList(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/block/list");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if ("200".equals(code)) {
                String users = jsonObject.getString("users");
                List<ChatroomUserDto> list = JSON.parseArray(users, ChatroomUserDto.class);

                ArrayList<ChatroomUserDto> chatroomUserDtos = new ArrayList<>();
                for (ChatroomUserDto dto : list){

                    ChatroomUserDto chatroomDto = new ChatroomUserDto();
                    chatroomDto.setUserId(dto.getUserId());
                    chatroomDto.setTime(dto.getTime());

                    // 加密的用户id
                    String userId = dto.getUserId();
                    Long decodeUserId = N3d.decode(userId);
                    User user = userService.selectById(decodeUserId);
                    if (null != user) {
                        String nick = user.getNick();
                        String avatar = user.getAvatar();
                        chatroomDto.setAvatar(avatar);
                        chatroomDto.setNick(nick);
                    }

                    chatroomUserDtos.add(chatroomDto);
                }

                return FsResponseGen.successData(chatroomUserDtos);
            }


            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 添加封禁聊天室成员
     * @return
     */
    @RequestMapping("/chatroom/user/block/add")
    @ResponseBody
    public FsResponse blockAdd(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/block/add");

            String minute = request.getMinute();
            if (StringUtils.isBlank(minute)){
                return FsResponseGen.failMsg("请输入封禁时长，区间【0 ~ 43200】，单位为分钟");//封禁时长，以分钟为单位，最大值为43200分钟。
            }

            // 设置请求消息体参数
            String userId = request.getUserId();
            String chatroomId = request.getChatroomId();
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", userId));
            params.add(new BasicNameValuePair("chatroomId", chatroomId));

            params.add(new BasicNameValuePair("minute", minute));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if ("200".equals(code)) {
                // 封禁后需要把本地数据库中的用户数据删除
                Long decodeUserId = N3d.decode(userId);
                Long decodeChatroomId = N3d.decode(chatroomId);
                userJoinChatroomMapper.deleteChatroomMember(Long.toString(decodeChatroomId), Long.toString(decodeUserId));
            }

            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 移除封禁聊天室用户
     * @return
     */
    @RequestMapping("/chatroom/user/block/rollback")
    @ResponseBody
    public FsResponse blockRollback(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/block/rollback");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId",  request.getUserId()));
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 添加聊天室白名单成员
     * @return
     */
    @RequestMapping("/chatroom/user/whitelist/add")
    @ResponseBody
    public FsResponse whitelistAdd(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/whitelist/add");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", request.getUserId()));
            params.add(new BasicNameValuePair("chatroomId", request.getChatroomId()));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    public static void main(String[] args) {
        try {
            System.out.println(N3d.encode(Long.valueOf(286214)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 移除聊天室白名单成员
     * @return
     */
    @RequestMapping("/chatroom/user/whitelist/remove")
    @ResponseBody
    public FsResponse whitelistRemove(@RequestBody ChatroomRequest request) {

        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/whitelist/remove");
            String chatroomId = request.getChatroomId();
            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", request.getUserId()));
            params.add(new BasicNameValuePair("chatroomId", chatroomId));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 查询聊天室白名单
     * @return
     */
    @RequestMapping("/chatroom/user/whitelist/query")
    @ResponseBody
    public FsResponse whitelistQuery(@RequestBody ChatroomRequest request) {


        // 查询本地储存的聊天室管理员
        List<MessageChatroomAdminUser> list = messageChatroomAdminUserMapper.selectAll();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",200);
        JSONArray jsonArray=new JSONArray();
        for(MessageChatroomAdminUser adminUser:list){
            try {
                jsonArray.add(N3d.encode(Long.valueOf(adminUser.getUserId())));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        jsonObject.put("users",jsonArray);

        return FsResponseGen.successData(jsonObject.toJSONString());

//        try {
//            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/whitelist/query");
//            String chatroomId = request.getChatroomId();
//
//            // 设置请求消息体参数
//            List<NameValuePair> params = new ArrayList<>();
//            params.add(new BasicNameValuePair("chatroomId", chatroomId));
//            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
//
//            String response = rongCloudApplication.executeReq(httpPost);
//            return rongCloudApplication.judgmentResults(response);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return FsResponseGen.gen(false);
    }



    /**
     * 模糊查询聊天室的成员
     * @return
     */
    @RequestMapping("/chatroom/queryUserChatroom")
    @ResponseBody
    public FsResponse queryUserChatroom(@RequestBody ChatroomUserRequest request) {

        try {

            // 模糊查询聊天室内成员
            String chatroomId = request.getChatroomId();
            if (StringUtils.isBlank(chatroomId)) {
                return FsResponseGen.failMsg("参数错误，聊天室ID不存在！");
            }
            // 查询聊天室是否存在
            MessageChatroom chatroom = new MessageChatroom();
            chatroom.setChatroomId(chatroomId);
            MessageChatroom messageChatroom = messageChatroomMapper.selectOne(chatroom);
            if (null == messageChatroom) {
                return FsResponseGen.failMsg("聊天室不存在！");
            }

            String appid = request.getAppid();
            String nick = request.getNick();
            Long decodeChatroomId = N3d.decode(chatroomId);

            List<User> list = userJoinChatroomMapper.queryUserByParam(Long.toString(decodeChatroomId), appid, nick);
            return FsResponseGen.successData(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 查询用户是否在该聊天室
     * @return
     */
    @RequestMapping("/chatroom/queryUserInChatroom")
    @ResponseBody
    public FsResponse queryUserInChatroom(@RequestBody ChatroomRequest request) {

        try {

            Long userId = getUserId();
            String chatroomId = request.getChatroomId();
            Long decodeChatroomId = N3d.decode(chatroomId);

            UserJoinChatroom user = userJoinChatroomMapper.queryUserInChatroom(userId, Long.toString(decodeChatroomId));
            if (null == user) {
                return FsResponseGen.successData(false);
            }
            return FsResponseGen.successData(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 用户申请进入聊天室
     * @return
     */
    @RequestMapping("/chatroom/userApplyForChatroom")
    @ResponseBody
    public FsResponse userApplyForChatroom(@RequestBody ChatroomRequest request) {

        try {

            // 首先查询该用户是否已申请过
            Long userId = getUserId();
            if (null == userId) {
                return FsResponseGen.failMsg("参数错误[userID]");
            }

            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            String chatroomId = request.getChatroomId();
            Long decodeChatroomId = N3d.decode(chatroomId);
            String encodeChatroom = Long.toString(decodeChatroomId);

            UserJoinChatroomApply user = userJoinChatroomApplyMapper.queryApplyForChatroom(userId, encodeChatroom);

            if (null == user) {

                // 新增申请记录
                UserJoinChatroomApply joinChatroom = new UserJoinChatroomApply();
                joinChatroom.setUserId(userId);

                joinChatroom.setChatroomId(encodeChatroom);
                joinChatroom.setCreateTime(new Date());
                joinChatroom.setStatus(UserJoinChatroom.STATUS_AUDIT);
                userJoinChatroomApplyMapper.insert(joinChatroom);

                return FsResponseGen.successMsg("申请成功，请等待审核结果！");

            }



            // 用户审核状态
            String status = user.getStatus();
            if (UserJoinChatroom.STATUS_APPROVED.equals(status)) {
                // 查询是否已有聊天室成员记录, 如果有申请成功记录没有成员记录直接更新申请状态为待审核（针对删除成员后重新申请的情况）
                UserJoinChatroom userJoinChatroom = userJoinChatroomMapper.queryApplyForChatroom(userId, encodeChatroom);
                if (null == userJoinChatroom) {
                    UserJoinChatroomApply chatroom = new UserJoinChatroomApply();
                    chatroom.setId(user.getId());
                    chatroom.setStatus(UserJoinChatroom.STATUS_AUDIT);
                    userJoinChatroomApplyMapper.updateByPrimaryKeySelective(chatroom);
                    return FsResponseGen.successMsg("申请成功，请等待审核结果！");
                }

                return FsResponseGen.successMsg("申请成功！");
            }
            if (UserJoinChatroom.STATUS_AUDIT.equals(status)) {
                return FsResponseGen.successMsg("审核中！");
            }
            if (UserJoinChatroom.STATUS_REJECTION.equals(status)) {
                UserJoinChatroomApply chatroom = new UserJoinChatroomApply();
                chatroom.setId(user.getId());
                chatroom.setStatus(UserJoinChatroom.STATUS_AUDIT);
                userJoinChatroomApplyMapper.updateByPrimaryKeySelective(chatroom);
                return FsResponseGen.successMsg("申请成功，请等待审核结果！");
            }
            if (UserJoinChatroom.STATUS_REJECTED.equals(status)) {
                return FsResponseGen.successMsg("拒绝申请加入！");
            }

            return FsResponseGen.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FsResponseGen.gen(false);
    }


    public String decodeChatroomId(String chatroomId){
        try {
            Long decodeChatroomId = N3d.decode(chatroomId);
            return Long.toString(decodeChatroomId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chatroomId;
    }


    @PostMapping("group/send/img")
    public FsResponse sendImgRobot(MessageSendGroupRequest params, MultipartFile file) throws Exception {

        String path = ossService.upload(file.getInputStream());

        if (StringUtils.isBlank(path)) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_PARAM_ERROR);
        }

        path = "http://" + configSet.getOss().getBucketName() + "." + configSet.getOss().getEndpoint() + "/" + path;

        System.out.println(path);

        if (Objects.isNull(params.getGroupId()) || Objects.isNull(params.getUserId())
                || StringUtils.isBlank(params.getSign())) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_PARAM_ERROR);
        }

        //校验key
        if (!StringUtils.equals(MD5Util.string2MD5(params.getUserId() + configSet.getKey().getMessage()), params.getSign())) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_KEY_ERROR);
        }


        User user = userService.selectById(N3d.decode(params.getUserId()));
        if (Objects.isNull(user)) {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_PARAM_ERROR);
        }


        MessageBodyDto dto = new MessageBodyDto();

        MessageBodyDto.Ext ext = dto.new Ext();
        ext.setAvatar(user.getAvatar());
        ext.setNick(user.getNick());
        ext.setUserId(String.valueOf(params.getUserId()));

        MessageBodyDto.Body body = dto.new Body();
        body.setFileName(path);
        body.setRemotePath(path);
        BufferedImage image = ImageIO.read(file.getInputStream());
        body.setSize(image.getWidth() + "," + image.getHeight());

        MessageBodyDto.Data data = dto.new Data();
        data.setExt(ext);
        data.setBody(body);
        data.setChatType(2);
        data.setMsgType(2002);
        data.setMsgId(UUID.randomUUID().toString() + robot_sign);
        data.setFrom(String.valueOf(params.getUserId()));
        data.setTo(String.valueOf(params.getGroupId()));
        data.setTimestamp(System.currentTimeMillis());


        dto.setData(data);
        dto.setType(2000);

        //发送消息
        imApiService.sendRobotMsg(2, params.getGroupId().longValue(), URLEncoder.encode(JSON.toJSONString(dto)));


        Message save = new Message();
        save.setContent(URLEncoder.encode(JSON.toJSONString(dto)));
        save.setUserId(Long.valueOf(params.getUserId()));
        save.setReferType(2);
        save.setReferId(params.getGroupId().longValue());
        save.setMessageId(data.getMsgId());
        save.setTime(System.currentTimeMillis());
        //保存历史消息
        messageService.save(save, false);


        return FsResponseGen.success();

    }






}
